package com.biovr.backend.security;

import com.biovr.backend.config.ErrorCode;
import com.biovr.backend.domain.User;
import com.biovr.backend.repository.UserRepository;
import com.biovr.backend.utils.ResponseFactory;
import com.biovr.backend.utils.RestResponse;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by monodev on 2017/6/17.
 */
@RestController
public class AuthController {
    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private AuthService authService;
    @Autowired
    private UserRepository userRepository;

    /**
     * Auth(Login)
     * @param request
     * @param authenticationRequest
     * @return
     * @throws AuthenticationException
     */
    @RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST)
    public RestResponse<?> createAuthenticationToken(javax.servlet.http.HttpServletRequest request,
                                                     @RequestBody JwtAuthenticationRequest authenticationRequest) throws AuthenticationException {
        String pwd = authenticationRequest.getPassword();
        final String token = authService.login(request,authenticationRequest.getUsername(), authenticationRequest.getPassword());
        if (token==null){
            return ResponseFactory.createErrorResult("用户名或密码错误");
        }
        // Return the token
        return  ResponseFactory.createSuccessResult(new JwtAuthenticationResponse(token)) ;
    }

    @RequestMapping(value = "${jwt.route.authentication.refresh}", method = RequestMethod.GET)
    public RestResponse<?> refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws AuthenticationException{
        String token = request.getHeader(tokenHeader);
        String refreshedToken = authService.refresh(token);
        if(refreshedToken == null) {
            return ResponseFactory.createErrorResult(ErrorCode.ILLEGAL_PARAMS);
        } else {
            return ResponseFactory.createSuccessResult(new JwtAuthenticationResponse(refreshedToken));
        }
    }

    @RequestMapping(value = "${jwt.route.authentication.register}", method = RequestMethod.POST)
    public RestResponse<User> register(@RequestBody User user) throws AuthenticationException{
        if(userRepository.findByUsername(user.getUsername())!=null) {
            return  ResponseFactory.createErrorResult("用户名已存在");
        }
        User addedUser = authService.register(user);
        return ResponseFactory.createSuccessResult(addedUser );
    }
}
